# yourapp/views.py

import jwt
import datetime
from django.conf import settings
from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
import os
from django.contrib.auth.models import User
from .models import UserExtraction
# 生成 JWT


def generate_jwt(user):
    payload = {
        'user_id': user.id,
        'username': user.username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24),  # 24小时过期
        'iat': datetime.datetime.utcnow(),
    }
    # 使用 SECRET_KEY 签名
    token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
    return token

# 验证 JWT 中间件（装饰器）


def jwt_required(view_func):
    def wrapper(request, *args, **kwargs):
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        if not auth_header.startswith('Bearer '):
            return JsonResponse({'error': 'Authorization header missing or invalid'}, status=401)

        token = auth_header.split(' ')[1]
        try:
            payload = jwt.decode(
                token, settings.SECRET_KEY, algorithms=['HS256'])
            request.user_id = payload['user_id']
            request.username = payload['username']
        except jwt.ExpiredSignatureError:
            return JsonResponse({'error': 'Token expired'}, status=401)
        except jwt.InvalidTokenError:
            return JsonResponse({'error': 'Invalid token'}, status=401)

        return view_func(request, *args, **kwargs)
    return wrapper


@csrf_exempt
@require_http_methods(["POST"])
def api_login(request):
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
    except:
        return JsonResponse({'msg': 'Invalid JSON', "code": 400, "data": None})

    user = authenticate(request, username=username, password=password)
    if user is not None:

        token = generate_jwt(user)
        # 保存用户提取信息
        user_extraction = UserExtraction.objects.get_or_create(user_id=user.id)
        return JsonResponse({
            'msg': 'Login successful',
            'code': 200,
            'data': {
                'token': token,  # ← App/小程序保存这个 token
                'user': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'extraction': {
                        'id': user_extraction[0].id,
                        'user_id': user_extraction[0].user_id,
                        'avator': user_extraction[0].avator or '',
                        'phone': user_extraction[0].phone_number or '',
                        'level': user_extraction[0].level or 0,
                    },
                },

            }
        })
    else:
        return JsonResponse({'msg': 'Invalid credentials', "code": 401, "data": None})


@csrf_exempt
@jwt_required
@require_http_methods(["GET"])
def api_test(request):
    # 从 token 中获取用户信息（无数据库查询）
    print(f"✅ [JWT] 当前用户: ID={request.user_id}, 用户名={request.username}")

    return JsonResponse({
        'msg': 'You are logged in via JWT.',
        'code': 200,
        'data': {
            'id': request.user_id,
            'username': request.username,
        }
    })


# 注册接口
@csrf_exempt
@require_http_methods(["POST"])
def api_register(request):
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
    except:
        return JsonResponse({'msg': 'Invalid JSON', "code": 400, "data": None})

    if User.objects.filter(username=username).exists():
        return JsonResponse({'msg': 'Username already exists', "code": 400, "data": None})

    user = User.objects.create_user(
        username=username, password=password, email=email)
    return JsonResponse({'msg': 'User registered successfully', "code": 201, "data": {
        'id': user.id,
        'username': user.username,
        'email': user.email
    }})
